import time
from rich.progress import Progress, BarColumn, TextColumn, TimeRemainingColumn
from rich.console import Console
from rich import print as rprint

from task import Task


class TomatoTimer:
    def __init__(self, duration_minutes: int = 25):
        self.duration = duration_minutes * 60  # 转换为秒
        self.console = Console()

    def _show_notification(self, task: Task):
        """显示完成通知"""
        print("\a")  # 系统提示音
        rprint(f"\n[bold green]🎉 番茄钟完成![/bold green]")
        rprint(f"[green]任务 '{task.name}' 已完成 {task.completed_pomodoros + 1} 个番茄钟[/green]")
        rprint("[yellow]休息一下吧![/yellow]")

    def run(self, task: Task) -> bool:
        """运行番茄钟，返回是否成功完成（没有被中断）"""
        remaining = self.duration
        rprint(f"\n[bold]🍅 开始番茄钟[/bold]")
        rprint(f"[cyan]任务: {task.name}[/cyan]")
        rprint(f"[cyan]时长: {self.duration // 60} 分钟[/cyan]")
        rprint("[yellow]提示: 按 Ctrl+C 可中断番茄钟[/yellow]\n")

        try:
            with Progress(
                TextColumn("[progress.description]{task.description}"),
                BarColumn(),
                TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
                TimeRemainingColumn(),
                console=self.console,
                expand=True,
                transient=True,
            ) as progress:
                progress_task = progress.add_task(
                    f"[cyan]{task.name}[/cyan]", total=self.duration
                )
                while remaining > 0:
                    progress.update(progress_task, advance=1)
                    remaining -= 1
                    time.sleep(1)
            # 番茄钟完成
            self._show_notification(task)
            return True

        except KeyboardInterrupt:
            rprint("\n[yellow]⏹️  番茄钟已被中断[/yellow]")
            return False
